<template>

    <div class="group">
        <h2>留言板</h2>

        <!-- 留言输入表单 -->
        <div>
            <label for="message">输入留言：</label>
            <textarea v-model="char" :maxlength="maxChar" id="message" placeholder="请输入留言..."></textarea>
            <p>剩余字符：{{ residualChar }}</p>
            <button @click="submitMessage">提交留言</button>
        </div>

        <!-- 留言列表 -->
        <ul>
            <!-- 留言条目 -->
            <li v-for="(item, index) in messagesArr" :key="index">
                <MessageItem :message="item" @delete="deleteMessage(index)">
                    <!-- 自定义留言显示的插槽 -->
                    <template v-slot:default="slotProps">
                        <span>{{ slotProps.message }}</span>
                    </template>
                </MessageItem>
            </li>
        </ul>
    </div>

</template>

<script setup lang='ts'>
import { computed, ref } from 'vue';
import MessageItem from './compontents/MessageItem.vue';


const messagesArr = ref([]);
const char = ref('');

const maxChar = 100;
const residualChar = computed(() => {
    return maxChar - (char.value ? char.value.length : 0);
});


function submitMessage() {
    const inputValue = char.value.trim();
    if (inputValue && inputValue.length <= maxChar) {
        messagesArr.value.push(inputValue as never);
        char.value = ''; // Clear the input field  
    }
}

const deleteMessage = (index: number) => {
    messagesArr.value.splice(index, 1);
}

</script>


<style lang="scss" scoped>
.group {
    border: 3px solid skyblue;
    margin: 10px;
    padding: 10px;
}

div {
    margin-bottom: 20px;
}

label {
    display: block;
    margin-bottom: 5px;
}

textarea {
    width: 100%;
    height: 100px;
    padding: 8px;
    margin-bottom: 10px;
    border: 1px solid #ccc;
    border-radius: 4px;
    resize: none;
}

button {
    background-color: #28a745;
    color: white;
    padding: 10px 20px;
    border: none;
    cursor: pointer;
    border-radius: 4px;
}

button:hover {
    background-color: #218838;
}

p {
    margin-top: 0;
    font-size: 0.9em;
    color: #888;
}

ul {
    list-style-type: none;
    padding: 0;
}

li {
    margin-bottom: 10px;
    padding: 10px;
    border: 1px solid #ddd;
    border-radius: 4px;
    background-color: #f9f9f9;
}
</style>